<template>
  <div>
    <section class="hero is-primary" id="levelbar">
      <div class="hero-body">
        <div class="container">
          <div class="tile is-ancestor">
            <div class="tile">
              <div class="tile is-parent">
                <article class="tile is-child notification is-primary">
                  <h1 class="title">
                    {{article.name}}
                  </h1>
                  <h2 class="subtitle">
                    {{article.description}}
                  </h2>
                </article>
                <article class="tile is-child notification is-primary">
                  <div class="level is-mobile">
                    <div class="level-item has-text-centered" v-for="content in basic">
                      <div>
                        <p class="heading">{{content.split(':')[0]}}</p>
                        <p class="title">{{content.split(':')[1]}}</p>
                      </div>
                    </div>
                  </div>
                </article>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
    <div class="tile is-ancestor" v-if="article.hasData ===0">
      <div class="tile is-vertical">
        <div class="tile">
          <div class="tile is-parent is-vertical">
            <article class="tile is-child is-primary box">
              <p class="title">{{$t("message.upload")}}...</p>
              <p class="subtitle">{{$t("message.uploadWarn")}}</p>
              <table class="table">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Instrument</th>
                    <th></th>
                    <th></th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>Name</th>
                    <th>Instrument</th>
                    <th></th>
                    <th></th>
                  </tr>
                </tfoot>
                <tbody>
                  <tr v-for="file in files">
                    <td>{{file.name}}</td>
                    <td>{{file.type}}</td>
                    <td class="is-icon">
                      <a>
                        <i class="fa fa-edit"></i>
                      </a>
                    </td>
                    <td class="is-icon">
                      <a @click.prevent="$refs.upload.remove(file)">
                        <i class="fa fa-remove"></i>
                      </a>
                    </td>
                  </tr>
                </tbody>
              </table>
              <file-upload ref="upload" v-model="files" :post-action="postAction" :multiple="multiple" @input-file="inputFile" @input-filter="inputFilter">
                <p class="button is-primary">{{$t("message.upload")}}</p>
              </file-upload>
              <button v-show="!$refs.upload || !$refs.upload.active" @click.prevent="$refs.upload.active = true , alterStatus()" class="button is-primary">{{$t("message.startUpload")}}</button>
              <button v-show="$refs.upload && $refs.upload.active" @click.prevent="$refs.upload.active = false" class="button is-danger">{{$t("message.stopUpload")}}</button>
              <span v-show="status && $refs.upload && $refs.upload.uploaded">{{$t("message.uploadedMessage")}}</span>
            </article>
          </div>
        </div>
      </div>
    </div>
    <div class="tile is-ancestor" v-else>
      <div class="tile is-vertical">
        <div class="tile">
          <div class="tile is-parent is-vertical">
            <article class="tile is-child is-primary box">
              <p class="title">{{$t("message.catalogue")}}...</p>

              <table class="table">
                <thead>
                  <tr>
                    <th>{{$t("message.fileName")}}</th>
                    <th>{{$t("message.size")}}</th>
                    <th></th>
                    <th></th>
                    <th></th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>{{$t("message.fileName")}}</th>
                    <th>{{$t("message.size")}}</th>
                    <th></th>
                    <th></th>
                    <th></th>
                  </tr>
                </tfoot>
                <tbody>
                  <tr v-for="content in catalogue">
                    <td>{{content.split(' ')[1]}}</td>
                    <td>{{content.split(' ')[0]}}</td>
                    <td class="is-icon">
                      <a @click="download(content.split(' ')[1])">
                        <i class="fa fa-eye"></i>
                      </a>
                    </td>
                    <td class="is-icon">
                      <a @click="remove(content.split(' ')[1])">
                        <i class="fa fa-remove"></i>
                      </a>
                    </td>
                    <td class="is-icon">
                      <a @click="alter(content.split(' ')[1])">
                        <i class="fa fa-edit"></i>
                      </a>
                    </td>
                  </tr>
                </tbody>
              </table>
            </article>
            <article class="tile is-child box" v-if="article.descriptive_statistics ===0">
              <h1 class="title">{{$t("message.descriptivestatistics")}}</h1>
              <div class="block styles-box">
                <p class="subtitle">{{$t("message.descriptivestatisticsMessage")}}</p>
                <button class="button" @click="descriptive()">Start</button>
              </div>
            </article>
            <article class="tile is-child box" v-else>
              <h1 class="title">{{$t("message.descriptivestatistics")}}</h1>
              <div class="block styles-box">

                <table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth">
                  <thead>
                    <tr>
                      <th v-for="field in descriptiveStatistics.schema.fields">{{field.name}}</th>
                    </tr>
                  </thead>
                  <tfoot>
                    <tr>
                      <th v-for="field in descriptiveStatistics.schema.fields">{{field.name}}</th>
                    </tr>
                  </tfoot>
                  <tbody>
                    <tr v-for="field in descriptiveStatistics.data">
                      <td v-for="value in field">
                        {{value}}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </article>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import Vue from 'vue'
import { Tabs, TabPane } from 'vue-bulma-tabs'
import ProgressBar from 'vue-bulma-progress-bar'
import Chart from 'vue-bulma-chartjs'
import VueUploadComponent from 'vue-upload-component'
import ImageCompressor from '@xkeshi/image-compressor'
import DATAModals from './modals/DATAModal'
import axios from 'axios'
import Message from 'vue-bulma-message'
const MessageComponent = Vue.extend(Message)
const openMessage = (propsData = {
  title: '',
  message: '',
  type: '',
  direction: '',
  duration: 1500,
  container: '.messages'
}) => {
  return new MessageComponent({
    el: document.createElement('div'),
    propsData
  })
}
axios.defaults.baseURL = 'http://139.224.118.74:8080/query'
const DATAModalComponent = Vue.extend(DATAModals)

const openDATAModal = (propsData = {
  visible: true
}) => {
  return new DATAModalComponent({
    el: document.createElement('div'),
    propsData
  })
}
export default {
  components: {
    Tabs,
    TabPane,
    Chart,
    ProgressBar,
    FileUpload: VueUploadComponent
  },
  props: {
    info: Object
  },
  data () {
    return {
      basic: null,
      descriptiveStatistics: {
        schema: {
          fields: []
        },
        data: [
          {}
        ]
      },
      showDataModal: false,
      DataModal: null,
      hasDataSet: false,
      status: false,
      dsShow: false,
      catalogue: null,
      article: {},
      labels: ['Sleeping', 'Designing', 'Coding', 'Cycling'],
      data: [20, 40, 5, 35],
      options: {
        segmentShowStroke: false
      },
      backgroundColor: [
        '#1fc8db',
        '#fce473',
        '#42afe3',
        '#ed6c63',
        '#97cd76'
      ],

      labels_2: ['April', 'May', 'June', 'Jule', 'August', 'September', 'October', 'November', 'December'],
      data_2: [1, 9, 3, 4, 5, 6, 7, 8, 2].map(e => (Math.sin(e) * 25) + 25),

      labels_3: ['May', 'June', 'Jule', 'August', 'September', 'October', 'November'],
      data_3: [
        [65, 59, 90, 81, 56, 55, 40],
        [28, 48, 40, 19, 88, 27, 45]
      ],
      options_3: {
        tooltips: {
          mode: 'label'
        }
      },
      backgroundColor_3: [
        'rgba(31, 200, 219, 1)',
        'rgba(151, 205, 118, 1)'
      ],
      series: ['Product A', 'Product B'],
      files: [],
      multiple: true,
      postAction: 'http://139.224.118.74:8080/query/article/' + this.$store.state.app.personal.user.userId + '/' + JSON.parse(window.sessionStorage.getItem('personal.projects.article')).articleId + '/' + 'upload',
      putAction: 'http://139.224.118.74:8080/query/article/upload',
      headers: {
        'Access-Control-Allow-Origin': 'http://139.224.118.74:8080/query',
        'Authorization': window.localStorage.getItem('auth-token')
      }
    }
  },
  mounted () {
    this.article = JSON.parse(window.sessionStorage.getItem('personal.projects.article'))
    // this.article = this.$route.query.article
    this.$route.query.article = this.article
    console.log(this.article.status)
    const self = this
    if (this.article.hasData === 1) {
      this.getIndex()
      .then(function (response) {
        // 将第一个数据删除
        response.data.splice(0, 1)
        self.catalogue = response.data
        self.getBasic()
        console.log('开始匹配')
        const reg = /(?:.data)$/g
        const result = _.filter(self.catalogue, content => {
          return reg.test(content.split(' ')[1])
        })
        console.log(result)
        if (result.length !== 0) {
          self.hasDataSet = true
        }
        if (self.article.hasData === 1 && self.hasDataSet) {
          self.descriptive()
        } else {
          if (!self.status) {
            openMessage({
              message: '没有数据集',
              type: 'failure',
              duration: 1000,
              showCloseButton: true
            })
          }
        }
      })
      .catch(function (error) {
        console.log(error)
      })
    }
  },
  methods: {
    remove: function (filename) {
      const self = this
      axios.get('/article/remove/' + this.$store.state.app.personal.user.userId + '/' + JSON.parse(window.sessionStorage.getItem('personal.projects.article')).articleId + '/' + filename)
      .then(function (response) {
        self.getIndex()
        .then(function (response) {
          // 将第一个数据删除
          response.data.splice(0, 1)
          self.catalogue = response.data
          // 判断是否把文件都删除了
          if (self.catalogue.length === 0) {
            // 设置没有数据了
            self.$data.article.hasData = 0
          }
          console.log('开始匹配')
          // 如果删除的是.data数据集
          const datareg = /(?:.data)$/g
          const headerReg = /(?:header.names)$/g
          // 如果删除得是数据集和头文件，就要初始化
          if (datareg.test(filename) || headerReg.test(filename)) {
            self.descriptiveStatistics = {
              schema: {
                fields: []
              },
              data: [
                {}
              ]
            }
            self.basic = null
            self.article.descriptiveStatistics = 0
            self.article.hasData = 0
            window.sessionStorage.setItem('personal.projects.article', JSON.stringify(self.$data.article))
            self.$store.dispatch('alterArticleAndCommond', {
              userId: self.$store.state.app.personal.user.userId,
              article: self.$data.article
            })
            self.$store.dispatch('alterArticle', {
              articleId: JSON.parse(window.sessionStorage.getItem('personal.projects.article')).articleId,
              key: 'hasData',
              value: 0
            })
          }
        })
        .catch(function (error) {
          console.log(error)
        })
      })
      .catch(function (error) {
        console.log(error)
      })
    },
    getIndex: function () {
      return axios.get('/article/index/' + this.$store.state.app.personal.user.userId + '/' + JSON.parse(window.sessionStorage.getItem('personal.projects.article')).articleId)
    },
    getBasic: function () {
      const self = this
      axios.get('/article/basic/' + this.$store.state.app.personal.user.userId + '/' + JSON.parse(window.sessionStorage.getItem('personal.projects.article')).articleId)
      .then(function (response) {
        self.basic = response.data
      })
      .catch(function (error) {
        console.log(error)
      })
    },
    descriptive: function () {
      const self = this
      axios.get('/article/desc/statistics/' + this.$store.state.app.personal.user.userId + '/' + this.$route.query.article.articleId)
      .then(function (response) {
        console.log(typeof (response.data[0]))
        self.descriptiveStatistics = JSON.parse(response.data[0])
        self.article.descriptiveStatistics = 1
      })
      .catch(function (error) {
        console.log(error)
      })
    },
    closeDATAModal () {
      this.showModal = false
    },
    openDATAModal () {
      const DATAModal = this.DATAModal || (this.DATAModal = openDATAModal({
        title: 'Parameter',
        info: {},
        url: this.$store.state.pkg.homepage
      }))
      DATAModal.$children[0].active()
    },
    read: function (path) {
      const { href } = this.$router.resolve({
        name: 'content',
        query: {
          content: '内容'
        }
      })
      window.open(href, '_blank')
    },
    download: function (path) {
      const playload = {
        filename: path,
        userId: this.$store.state.app.personal.user.userId,
        articleId: this.$route.query.article.articleId
      }
      this.$store.dispatch('downloadfile', playload)
    },
    alterStatus: function () {
      this.status = true
    },
    inputFilter: function (newFile, oldFile, prevent) {
      if (newFile && !oldFile) {
        // Before adding a file
        // 添加文件前
        // Filter system files or hide files
        // 过滤系统文件 和隐藏文件
        if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
          return prevent()
        }
        // Filter php html js file
        // 过滤 php html js 文件
        if (!/\.(csv?|data?|names?|)$/i.test(newFile.name)) {
          return prevent()
        }
        // Automatic compression
        // 自动压缩
        if (newFile.file && newFile.type.substr(0, 6) === 'image/' && this.autoCompress > 0 && this.autoCompress < newFile.size) {
          newFile.error = 'compressing'
          const imageCompressor = new ImageCompressor(null, {
            convertSize: Infinity,
            maxWidth: 512,
            maxHeight: 512
          })
          imageCompressor.compress(newFile.file)
            .then((file) => {
              this.$refs.upload.update(newFile, { error: '', file, size: file.size, type: file.type })
            })
            .catch((err) => {
              this.$refs.upload.update(newFile, { error: err.message || 'compress' })
            })
        }
      }
      if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
        // Create a blob field
        // 创建 blob 字段
        newFile.blob = ''
        let URL = window.URL || window.webkitURL
        if (URL && URL.createObjectURL) {
          newFile.blob = URL.createObjectURL(newFile.file)
        }
        // Thumbnails
        // 缩略图
        newFile.thumb = ''
        if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
          newFile.thumb = newFile.blob
        }
      }
    },
    inputFile: function (newFile, oldFile) {
      if (newFile && oldFile && !newFile.active && oldFile.active) {
        console.log('response', newFile.response)
        if (newFile.xhr) {
          console.log('status', newFile.xhr.status)
          if (newFile.xhr.status === 200) {
            this.$store.dispatch('alterArticle', {
              articleId: JSON.parse(window.sessionStorage.getItem('personal.projects.article')).articleId,
              key: 'hasData',
              value: 1
            })
          }
        }
      }
    }
  },
  computed: {
    pieData () {
      return {
        labels: this.labels,
        datasets: [{
          data: this.data,
          backgroundColor: this.backgroundColor
        }]
      }
    },

    waveData () {
      return {
        labels: this.labels_2,
        datasets: [{
          label: 'My Radar',
          data: this.data_2,
          backgroundColor: this.backgroundColor[0]
        }]
      }
    },

    seriesData () {
      let data = {
        labels: this.labels_3
      }
      data.datasets = this.series.map((e, i) => {
        return {
          data: this.data_3[i],
          label: this.series[i],
          borderColor: this.backgroundColor_3[i].replace(/1\)$/, '.5)'),
          pointBackgroundColor: this.backgroundColor_3[i],
          backgroundColor: this.backgroundColor_3[i].replace(/1\)$/, '.5)')
        }
      })
      return data
    }
  },

  created () {
    setInterval(() => {
      // https://vuejs.org/guide/list.html#Mutation-Methods
      this.data_2.unshift(this.data_2.pop())
    }, 1000)
  }

}
</script>
<style lang="scss" scoped>
#levelbar {
  margin-bottom: 1em;
}
.button {
  margin: 5px 0 0;
}
</style>
